//
//  HomeBaseDetailViewController.m
//  GiftNote
//
//  Created by lanou on 15/8/12.
//  Copyright (c) 2015年 GN. All rights reserved.
//

#import "HomeBaseDetailViewController.h"
#import "HomeHeader.h"
#import "HomeDetailHeadView.h"
#import "LORequestManger.h"
#import "HomeDetailModel.h"
#import "HomeDetailBuyViewController.h"
#import "MBProgressHUD+MJ.h"
#import "FMDatabase.h"

@interface HomeBaseDetailViewController ()<UIWebViewDelegate, UIScrollViewDelegate>

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIWebView *webView;

@property (nonatomic, strong) HomeDetailHeadView *headView;
@property (nonatomic, strong) HomeDetailBuyViewController *buyVC;

@property (nonatomic, strong) UIBarButtonItem *rightBarButton;
@property (nonatomic, strong) HomeDetailModel *detailModel;

@property (nonatomic, strong) FMDatabase *db;

@end



@implementation HomeBaseDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatScrollView];
    [self readData];
    
    [self creatCollectionBarButton];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.title = @"攻略详情";
    //  改变标题的颜色
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                [UIColor whiteColor],
                                NSForegroundColorAttributeName, nil];
    [self.navigationController.navigationBar setTitleTextAttributes:attributes];
    //  改变返回按钮的颜色
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [MBProgressHUD showMessage:@"正在加载中...."];
    
    [self creatCollectionList];
}




#pragma mark --- 收藏按钮
- (void)creatCollectionBarButton{
    
    _rightBarButton = [[UIBarButtonItem alloc]initWithTitle:@"三" style:UIBarButtonItemStyleDone target:self action:@selector(addCollection:)];
    self.navigationItem.rightBarButtonItem = _rightBarButton;
}

- (void)addCollection:(UIBarButtonItem *)sender{
    
    if (_detailModel.ID) {
        [self addCollectionData:_detailModel];
    }
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    NSNotification *notification = [[NSNotification alloc] initWithName:@"添加攻略收藏" object:nil userInfo:nil];
    [center postNotification:notification];
    
}


#pragma mark --- 创建scrollView

- (void)creatScrollView{
    
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kHomeWidth, kHomeHeight )];
    _scrollView.delegate = self;
    _scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_scrollView];
    
    _headView = [[HomeDetailHeadView alloc]initWithFrame:CGRectMake(0, 0, kHomeWidth, 318 * (kHomeWidth + 128) / 700)];
    [_scrollView addSubview:_headView];
    
    _webView = [[UIWebView alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(_headView.frame) + 15, kHomeWidth - 20, 0)];
    _webView.delegate = self;
    [_scrollView addSubview:_webView];
    
    
}


#pragma mark --- 数据解析
- (void)readData{
    
    NSString *url = [kHomeDetail stringByAppendingString:_ID];
    [LORequestManger GET:url success:^(id response) {
        
        NSDictionary *dic = (NSDictionary *)response;
        NSDictionary *newDic = dic[@"data"];
        _detailModel = [[HomeDetailModel alloc]init];
        [_detailModel setValuesForKeysWithDictionary:newDic];
        _headView.detailModel = _detailModel;
        

        
        NSRange range1 = [_detailModel.content_html rangeOfString:@"<script type=\"text/javascript\">var"];
        NSRange range2 = [_detailModel.content_html rangeOfString:@"</script>\n</body>"];
        
        NSRange newRange = NSMakeRange(range1.location, range2.location - range1.location);
        NSString *replacedStr = [_detailModel.content_html substringWithRange:newRange];
        
        _detailModel.content_html = [_detailModel.content_html stringByReplacingOccurrencesOfString:replacedStr withString:@""];
        
        
        [_webView loadHTMLString:_detailModel.content_html baseURL:nil];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error:%@",error);
    }];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    
    CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
    _webView.frame = CGRectMake(0, CGRectGetMaxY(_headView.frame) + 15, kHomeWidth, height);
    _scrollView.contentSize = CGSizeMake(kHomeWidth, height + _headView.frame.size.height + 25 + kHomeHeight / 5);
    
    [MBProgressHUD hideHUD];
}


- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    if (![request.URL.relativeString isEqualToString:@"about:blank"] ) {
        
        _buyVC = [[HomeDetailBuyViewController alloc]init];
        [self.navigationController pushViewController:_buyVC animated:YES];
        NSString *string = [request.URL.relativeString substringFromIndex:30];
        _buyVC.ID = string;
        
        return NO;
    }
    return YES;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    CGFloat size = scrollView.contentOffset.y;
    
    if (size < -64) {
        _headView.imageView.frame = CGRectMake(size, size + 64, kHomeWidth - 2 * size, 318 * (kHomeWidth - 2 * size) / 700 - (size + 64));
    } else if (size > -64) {
        
    }
}


#pragma mark --- 收藏数据
- (void)creatCollectionList{
    
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]stringByAppendingPathComponent:@"Mine.db"];
    _db = [FMDatabase databaseWithPath:path];
    
    if (![_db open]) {
        NSLog(@"打开数据库失败");
    }
    
    
    [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS MineStrategyList (id integer PRIMARY KEY, Cover_image_url text, Title text, Content_html text)"];
}



- (void)addCollectionData:(HomeDetailModel *)detailModel{
    
    BOOL res = [_db executeUpdate:@"INSERT INTO MineStrategyList (id, Cover_image_url, Title, Content_html) VALUES (?,?,?,?)",detailModel.ID, detailModel.cover_image_url, detailModel.title, detailModel.content_html];
    
    if (res) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"收藏成功" message:@"提示" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
    } else {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"已经收藏过" message:@"提示" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
